﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using Motorway_Simulator.Components;
using System.Windows.Forms;
using Motorway_Simulator.GUI.Designer;


namespace Motorway_Simulator.GUI
{
    /// <summary>
    /// Main form MDI master class
    /// </summary>
    public partial class MotorWaySimulatorGUI : Form
    {
        /// <summary>
        /// Number of child forms
        /// </summary>
        private int childFormNumber = 0;

        /// <summary>
        /// Holds the direction
        /// </summary>
       private RoadUnit.Direction direction = RoadUnit.Direction.NORTH;

        /// <summary>
        /// Initializes a new instance of the <see cref="MotorWaySimulatorGUI"/> class.
        /// </summary>
        public MotorWaySimulatorGUI()
        {
            System.Console.ReadLine();
            InitializeComponent();
        }

        /// <summary>
        /// Exits the program
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStrip.Visible = toolBarToolStripMenuItem.Checked;
        }

        /// <summary>
        /// Event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            statusStrip.Visible = statusBarToolStripMenuItem.Checked;
        }

        /// <summary>
        /// Event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        /// <summary>
        /// Event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        /// <summary>
        /// Event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        /// <summary>
        /// Event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.ArrangeIcons);
        }

        /// <summary>
        /// Closes all child forms
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in MdiChildren)
            {
                childForm.Close();
            }
        }

        /// <summary>
        /// Open a new design panel object
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void designToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form[] forms = this.MdiChildren;
            bool isDesignPanelActivated = false;
            foreach (Form form in forms)
            {   // Loop through all opened forms
                if (form is DesignPanel)
                {
                    // Find if design panel is active
                    isDesignPanelActivated = true;
                    break;
                }
            }
            if (!isDesignPanelActivated)
            {
                // If none active, create a new design panel
                DesignPanel childForm = new DesignPanel(roadUnitListView);
                childForm.MdiParent = this;

                // Set method call back
                childForm.RoadUnitOrientationCallback = new DesignPanel.RoadUnitOrientationDelegate(RoadUnitOrientationCallBack);
                childForm.StatusLabelCallBack = new DesignPanel.StatusLabelDelegate(SetStatusLabel);
                childForm.Text = "DesignPanel " + childFormNumber++;
                childForm.Show();
            }
            else
            {
                MessageBox.Show("Only allow one Design Panel opened at a time");
            }
        }

        /// <summary>
        /// Creatte a new simulation form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simulationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openSimulationMenuItem_Click(sender, e);
           
        }

        /// <summary>
        /// Design tool box handling
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void designToolBoxToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (designToolBoxPanel.Visible)
            {
                designToolBoxToolStripMenuItem.Checked = false;
                designToolBoxPanel.Visible = false;
                
            }
            else

            { designToolBoxPanel.Visible = true; 
              designToolBoxToolStripMenuItem.Checked = false; }
            this.Refresh();
          
        }

        /// <summary>
        /// Event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void playToolStripButton_Click(object sender, EventArgs e)
        {
           object o = this.ActiveMdiChild;
           if (o is Simulator.SimulationForm)
           {
               Simulator.SimulationForm form = (Simulator.SimulationForm)o;
               form.Play();
           }
        }

        
        /// <summary>
        /// Change the zoom level
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">event</param>
        private void ZoomIndexChanged(object sender, EventArgs e)
        {
            string item = (string)zoomLevelComboBox.SelectedItem;
           item = item.Substring(0,item.Length -1);
            float zoomlevel = float.Parse(item);

            object o = this.ActiveMdiChild;
            if (o is Designer.DesignPanel)
            {
                DesignPanel p = (DesignPanel)this.ActiveMdiChild;
                p.DesignCanvas1.Zoom = zoomlevel;
            }
            else
            {
                
            }
            // Focus on roadUnitListView
            roadUnitListView.Focus();

            
        }

        /// <summary>
        /// Returns RoadUnitListView
        /// </summary>
        public ListView RoadUnitListView
        {
            get { return roadUnitListView; }
        }

        /// <summary>
        /// Callback function to set the Direction label
        /// </summary>
        /// <param name="roadUnitOrientation">Road unit orientation</param>
        public void RoadUnitOrientationCallBack(int roadUnitOrientation)
        {
            if (roadUnitOrientation == 0)      { 
                direction = RoadUnit.Direction.NORTH;
                directionLabel.Text = "North";
            }
            else if (roadUnitOrientation == 1) { 
                direction = RoadUnit.Direction.EAST;
                directionLabel.Text = "East";
            }
            else if (roadUnitOrientation == 2) { 
                direction = RoadUnit.Direction.SOUTH;
                directionLabel.Text = "South";
            }
            else if (roadUnitOrientation == 3) { 
                direction = RoadUnit.Direction.WEST;
                directionLabel.Text = "West";
            }
        }

        /// <summary>
        /// Sets the message label
        /// </summary>
        /// <param name="message">Message</param>
        public void SetStatusLabel(String message)
        {
            statusLabel.Text = message;
        }

        /// <summary>
        /// Handle event for deleting when checked.
        /// Notifies all design panel of the change
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Event</param>
        private void deleteCheckButton_CheckedChanged(object sender, EventArgs e)
        {
            Form[] forms = this.MdiChildren;
            foreach (Form childForm in forms)
            {
                if (childForm is DesignPanel)
                {
                    DesignPanel p = (DesignPanel)childForm;
                    p.isDelete = deleteCheckButton.Checked;
                    
                }
            }
        }


        /// <summary>
        /// Handles the Click event of the saveDesignMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void saveDesignMenuItem_Click(object sender, EventArgs e)
        {
            Form form = this.ActiveMdiChild;
            if (form is DesignPanel)
            {
                try
                {
                    // Open file dialog
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                    saveFileDialog.Filter = "Design files (*.dsg)|*.dsg|All Files (*.*)|*.*";
                    if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        string FileName = saveFileDialog.FileName;
                        DesignPanel designPanel = (DesignPanel)form;
                        // Call save design
                        bool isSaved = designPanel.SaveDesign(FileName);
                        // Check if save is successful
                        if (isSaved)
                        {
                            statusLabel.Text = "File saved.";
                        }
                        else
                        {
                            MessageBox.Show("Error saving file! It's possible that the file could be corrupted");
                            statusLabel.Text = "Error saving file! It's possible that the file could be corrupted";
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Error saving " + ex);
                }
            }
            else
            {
                MessageBox.Show("Active MDI child is not a Design Panel.\n " +
                    "Please select/open Design Panel first");
            }
        }

        /// <summary>
        /// Event handling of Open Design file
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Event</param>
        private void openDesignMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            openFileDialog.Filter = "Design files (*.dsg)|*.dsg|All Files (*.*)|*.*";
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = openFileDialog.FileName;

                // Create a new design panel
                DesignPanel childForm = new DesignPanel(roadUnitListView);
                childForm.MdiParent = this;

                // Set up delegation
                childForm.RoadUnitOrientationCallback = new DesignPanel.RoadUnitOrientationDelegate(RoadUnitOrientationCallBack);
                childForm.StatusLabelCallBack = new DesignPanel.StatusLabelDelegate(SetStatusLabel);
                childForm.Text = "DesignPanel " + childFormNumber++;
                bool isSuccessful = childForm.LoadDesign(FileName);

                if (isSuccessful)
                {
                    childForm.Show();
                }
                else
                {
                    childForm.Dispose();
                }
            }
        }

        /// <summary>
        /// Event handling of Saving Design Simulation file
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Event</param>
        private void saveDesignSimulationMenuItem_Click(object sender, EventArgs e)
        {
            // Get the form of the active design panel
            Form form = this.ActiveMdiChild;
            if (form is DesignPanel)
            {   // Make sure it's a design panel
                try
                {
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                    saveFileDialog.Filter = "Simulation files (*.sim)|*.sim|All Files (*.*)|*.*";   // Format
                    if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        string FileName = saveFileDialog.FileName;
                        DesignPanel designPanel = (DesignPanel)form;
                        // Call it's function and pass the file name to save as
                        bool isSaved = designPanel.SaveDesignSimulation(FileName);

                        if (isSaved)
                        {
                            statusLabel.Text = "File saved.";
                        }
                        else
                        {
                            MessageBox.Show("Error saving file! It's possible that the file could be corrupted");
                            statusLabel.Text = "Error saving file! It's possible that the file could be corrupted";
                        }
                    }


                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Error saving " + ex);
                }
            }
            else
            {
                MessageBox.Show("Active MDI child is not a Design Panel.\n " +
                    "Please select/open appropriate Design Panel first");
            }
        }

        private void openSimulationMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            openFileDialog.Filter = "Design files (*.sim)|*.sim|All Files (*.*)|*.*";
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string fileName = openFileDialog.FileName;

                // Create a new design panel
                Simulator.SimulationForm childForm = new Simulator.SimulationForm(fileName);
                childForm.MdiParent = this;

              
                childForm.Text = "Simulation Panel " + childFormNumber++;
                bool isSuccessful = childForm.LoadSimulation(fileName);

                if (isSuccessful)
                {
                    childForm.Show();
                }
                else
                {
                    childForm.Dispose();
                }
            }
        }

        private void stopToolStripButton_Click(object sender, EventArgs e)
        {
            object o = this.ActiveMdiChild;
            if (o is Simulator.SimulationForm)
            {
                Simulator.SimulationForm form = (Simulator.SimulationForm)o;
                form.Stop();
            }
        }

        private void restartToolStripButton_Click(object sender, EventArgs e)
        {
            object o = this.ActiveMdiChild;
            if (o is Simulator.SimulationForm)
            {
                Simulator.SimulationForm form = (Simulator.SimulationForm)o;
                form.Restart();
            }
        }

        private void pauseToolStripButton_Click(object sender, EventArgs e)
        {
            object o = this.ActiveMdiChild;
            if (o is Simulator.SimulationForm)
            {
                Simulator.SimulationForm form = (Simulator.SimulationForm)o;
                form.Pause();
            }
        }
            

    }
}
